export default {
	name: "applylist",
	setup(props, { emit }) {
		const router = VueRouter.useRouter();
		const route = VueRouter.useRoute();
		const listData = ref([])
		const currentUser = ref(JSON.parse(localStorage.getItem('user')));
        const dialogApply = ref(false);
        const currentProcess = ref({currentStep: 0, steps: [], records: []});
		// 状态映射配置
		const statusConfig = {
			approval: {
				pending: {
					text: '待处理',
					type: 'warning'
				},
				approved: {
					text: '已通过',
					type: 'success'
				},
				rejected: {
					text: '已驳回',
					type: 'danger'
				}
			},
			initiated: {
				processing: {
					text: '进行中',
					type: 'primary'
				},
				approved: {
					text: '已完成',
					type: 'success'
				},
				rejected: {
					text: '已驳回',
					type: 'danger'
				}
			}
		}

		// 获取列表数据
		const fetchData = async () => {
			const res = await gettodoList();
			if(!res) return ElMessage.error('数据为空');
			listData.value = res.map(item => ({
				...item,
				createdAt: window.validators.formatDate(item.createdAt)
			}))
		}

		// 状态显示逻辑
		const getTagType = (item) => {
			return statusConfig[item.type][item.status]?.type || 'info'
		}

		const getStatusText = (item) => {
			return statusConfig[item.type][item.status]?.text || '未知状态'
		}
		
        // 新增状态文本转换方法
        const statusText = (status) => {
            const map = {
                pending: '待处理',
                processing: '进行中',
                approved: '已通过',
                rejected: '已驳回',
                running: '执行中'
            }
            return map[status] || '未知状态'
        }

		// 进度步骤计算
		const totalSteps = (item) => {
			return item.type === 'initiated' ? (item.max || 0) : 0
		}
		
        const statusMap = { pending: '待审批', approved: '已通过', rejected: '已驳回', processing: '审批中' };
        //查看、处理流程
        const viewapply = async (row) => {
            //审核员处理自己的审批流程
            if(isAuditor.value && ['pending', 'processing'].includes(row.status)){
                router.push({name: 'applyDetail', params: { id: row.formId }});
                return
            }
            dialogApply.value = true
            const res = await getProcessDetail({formId: row.formId, rowid: row.dataid});
            if(!res) return;
            // 构造步骤数据
            const maxStep = Math.max(...res.approvalRecords.map(r => r.step), res.currentStep)
            const steps = []
            for (let step = 1; step <= maxStep; step++) {
                const record = res.approvalRecords.find(r => r.step === step)
                steps.push({
                    step: step,
                    approver: record?.approver,
                    status: record?.status || 'pending'
                })
            }
            currentProcess.value = {
                ...res,
                steps: steps,
                // 添加申请人信息
                applicant: { name: res.initiator?.name },
                // 添加申请时间
                createdAt: row.created_at,
                // 按时间降序排列审批记录
                approvalRecords: [...res.approvalRecords].sort((b, a) => new Date(b.createdAt) - new Date(a.createdAt)),
                isend: 
                    // 情况1：存在驳回记录
                    res.approvalRecords.some(r => r.status === 'rejected') || 
                    // 情况2：已完成所有步骤（当前步骤超过配置步骤数）
                    (res.currentStep >= row.max) ||
                    // 情况3：实际步骤数超过配置步骤数（容错处理）
                    (maxStep > row.max)
            }
        }
        
        // 步骤状态计算
        const getStepStatus = (step) => {
            const currentStep = currentProcess.value.currentStep
             if (currentProcess.value.isend && currentProcess.value.approvalRecords.some(r => r.status === 'rejected')) {
                return 'error'
            }
            if (step.step < currentStep) return 'success'
            if (step.step === currentStep) return 'process'
            return 'wait'
        }
        
        // 记录标签类型
        const getRecordTagType = (status) => {
            switch(status) {
                case 'approved': return 'success'
                case 'rejected': return 'danger'
                case 'pending': return 'warning'
                default: return 'info'
            }
        }
        
        const isAuditor = computed(() => currentUser.value.Role === 'shy');

		onMounted(fetchData)

		return {
			listData,
			isAuditor,
			getTagType,
			getStatusText,
			totalSteps,
			statusText,
            viewapply,
            dialogApply,
            currentProcess,
            statusMap,
            getStepStatus,
            getRecordTagType,
            currentUser
		}
	},
	
	template: `
    <!-- 流程状态弹窗 -->
    <el-dialog v-model="dialogApply" title="流程审核状态" width="60%">
        <div>
            <!-- 审批步骤 -->
            <el-steps :active="currentProcess.currentStep + 1" align-center>
                <!-- 添加发起人作为第一步 -->
                <el-step
                    title="发起人"
                    :description="currentProcess.applicant?.name || '申请人'"
                    status="success"
                />
                <el-step 
                    v-for="(step, index) in currentProcess.steps"
                    :key="index"
                    :title="'步骤' + (index + 1)"
                    :description="step.approver?.name || '未指定审批人'"
                    :status="getStepStatus(step)"
                />
            </el-steps>
    
            <!-- 审批记录 -->
            <el-divider content-position="left">审批记录</el-divider>
            <el-timeline>
                <!-- 发起人提交记录 -->
                <el-timeline-item :timestamp="$validators.formatDate(currentProcess.createdAt)" placement="top">
                    <el-tag type="success">发起</el-tag>
                    <span class="approver">{{ currentProcess.applicant?.name }}</span>
                </el-timeline-item>
    
                <!-- 审批记录 -->
                <el-timeline-item v-for="(record, index) in currentProcess.approvalRecords" :key="index" placement="top"
                    :timestamp="record.status === 'pending' ? '' : $validators.formatDate(record.createdAt)">
                    <el-tag :type="getRecordTagType(record.status)">{{ statusMap[record.status] }}</el-tag>
                    <span class="approver">{{ record.approver?.name || '系统自动' }}</span>
                    <div v-if="record.comment" class="comment">{{ record.comment }}</div>
                    <div v-else class="no-comment"></div>
                </el-timeline-item>
    
                <el-timeline-item placement="top" v-if="currentProcess.isend">已结束</el-timeline-item>
            </el-timeline>
            
        </div>
    </el-dialog>
	
	<div class="todo-list-container">
		<!-- 头部 -->
    	<div class="header row">
    		<div class="col-lg-2 col-md-0">&nbsp;</div>
    		<div class="col-lg-10 col-md-12">
    			<img class="icon-logo" src="/pc_static/logo.png" />
    		</div>
    	</div>
        <div style="text-align:center;color:#fff;"><h1>{{ isAuditor ? '待审批事项' : '我的申请' }}</h1></div>
		<!-- 列表主体 -->
		<div class="list-container">
			<el-card v-for="item in listData" :key="item.type + item.instanceId" class="list-item" shadow="hover">
				<div class="item-header">
					<div class="status-tag">
						<el-tag :type="getTagType(item)" effect="plain">
							{{ getStatusText(item) }}
						</el-tag>
					</div>
					<span class="form-name">{{ item.formName }}</span>
					<span class="time">{{ item.createdAt }}</span>
				</div>

				<div class="item-content">
					<!-- 审核员视角 -->
					<template v-if="item.type === 'approval'">
						<div class="meta-grid">
							<div class="meta-item">
								<span class="label">审批步骤</span>
								<span class="value">第 {{ item.step }} 步</span>
							</div>
							<div class="meta-item">
								<span class="label">发起人</span>
								<span class="value">{{ item.approverName }}</span>
							</div>
						</div>
					</template>

					<!-- 发起人视角 -->
					<template v-else>
						<div class="progress-container">
							<div class="meta-grid">
								<div class="meta-item">
									<span class="label">当前进度</span>
									<span class="value">{{ item.currentStep }}/{{ totalSteps(item) }}</span>
								</div>
								<div class="meta-item">
									<span class="label">流程状态</span>
									<span class="value">{{ statusText(item.status) }}</span>
								</div>
							</div>
							<el-steps :active="item.currentStep" simple>
								<el-step v-for="step in totalSteps(item)" :key="step" :title="'步骤'+ step" />
							</el-steps>
						</div>
					</template>
				</div>

				<div class="item-actions">
					<el-button :type="getRecordTagType(item.status)" size="small" @click="viewapply(item)">
						{{ isAuditor && ['pending', 'processing'].includes(item.status) ? '立即处理' : '查看详情' }}
					</el-button>
				</div>
			</el-card>

			<el-empty v-if="listData.length === 0" description="暂无相关数据" />
		</div>
	</div>

`
}